package com.zp.security.oauth2.exception;

import com.zp.common.base.constant.ResultCode;
import com.zp.common.base.resp.BaseResp;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.stereotype.Component;

/**
 * 自定义异常翻译器
 * UnsupportedGrantTypeException 不支持的授权类型异常 InvalidGrantException 用户名密码异常
 * 都继承自Oauth2Exception通过默认的异常翻译器处理，因此我们自定义实现异常翻译器从而返回想要的内同
 *
 * @author zp
 */
@Component
public class MyWebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    @Override
    public ResponseEntity translate(Exception e) throws Exception {
        BaseResp baseResp = doHandler(e);
        return new ResponseEntity<>(baseResp, HttpStatus.UNAUTHORIZED);
    }

    /**
     * 根据异常类型来自定义需要的返回信息
     *
     */
    public BaseResp  doHandler(Exception e){
        ResultCode resultCode = ResultCode.UNAUTHORIZED;
        if (e instanceof UnsupportedGrantTypeException){
            resultCode=ResultCode.UNSUPPORTED_GRANT_TYPE;
        }else if (e instanceof InvalidGrantException){
            resultCode=ResultCode.USERNAME_OR_PASSWORD_ERROR;
        }
        return new BaseResp<>(resultCode);
    }

}
